"use client"

import type React from "react"

import { useState, useRef } from "react"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Upload, File, X, Loader2 } from "lucide-react"
import { Progress } from "@/components/ui/progress"
import { apiCall } from "@/lib/mock-api"
import { toast } from "@/hooks/use-toast"
import SparkMD5 from "spark-md5"

interface UploadDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onUploadSuccess?: () => void
  parentFolderId?: number
}

// 最大文件大小：100MB
const MAX_FILE_SIZE = 100 * 1024 * 1024

// 计算文件 MD5
const calculateFileMD5 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const chunkSize = 2097152 // 2MB per chunk
    const chunks = Math.ceil(file.size / chunkSize)
    let currentChunk = 0
    const spark = new SparkMD5.ArrayBuffer()
    const fileReader = new FileReader()

    fileReader.onload = (e) => {
      spark.append(e.target?.result as ArrayBuffer)
      currentChunk++

      if (currentChunk < chunks) {
        loadNext()
      } else {
        resolve(spark.end())
      }
    }

    fileReader.onerror = () => {
      reject(new Error("文件读取失败"))
    }

    function loadNext() {
      const start = currentChunk * chunkSize
      const end = start + chunkSize >= file.size ? file.size : start + chunkSize
      fileReader.readAsArrayBuffer(file.slice(start, end))
    }

    loadNext()
  })
}

export function UploadDialog({ open, onOpenChange, onUploadSuccess, parentFolderId = 0 }: UploadDialogProps) {
  const [files, setFiles] = useState<File[]>([])
  const [uploading, setUploading] = useState(false)
  const [progress, setProgress] = useState(0)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const validateAndSetFiles = (fileList: FileList) => {
    const fileArray = Array.from(fileList)
    const oversizedFiles = fileArray.filter((file) => file.size > MAX_FILE_SIZE)
    const validFiles = fileArray.filter((file) => file.size <= MAX_FILE_SIZE)

    if (oversizedFiles.length > 0) {
      toast({
        title: "文件大小超出限制",
        description: "演示版本最多只能上传 100M 的文件",
        variant: "destructive",
        duration: 4000,
      })
    }

    setFiles(validFiles)
  }

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      validateAndSetFiles(e.target.files)
    }
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    if (e.dataTransfer.files) {
      validateAndSetFiles(e.dataTransfer.files)
    }
  }

  const handleUpload = async () => {
    if (files.length === 0) return

    setUploading(true)
    setProgress(0)

    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        
        // 计算文件 MD5
        const fileMd5 = await calculateFileMD5(file)
        
        // 第一步：尝试秒传（只传 MD5 和 parentId）
        const formData1 = new FormData()
        formData1.append("fileName", file.name)
        formData1.append("fileMd5", fileMd5)
        formData1.append("parentId", parentFolderId.toString())

        const quickUploadResult = await apiCall(
          "/api/files/upload",
          {
            method: "POST",
            body: formData1,
          },
          { code: 2 }, // 模拟秒传失败
        ).catch((error) => {
          console.error("秒传失败:", error)
          return { code: error?.cause || 2 }
        })

        // 如果秒传失败（code: 2），则上传完整文件
        if (quickUploadResult?.code === 2) {
          const formData2 = new FormData()
          formData2.append("file", file)
          formData2.append("fileName", file.name)
          formData2.append("fileMd5", fileMd5)
          formData2.append("parentId", parentFolderId.toString())

          await apiCall(
            "/api/files/upload",
            {
              method: "POST",
              body: formData2,
            },
            { code: 1, fileId: Math.floor(Math.random() * 1000000) },
          )
        }

        await new Promise((resolve) => setTimeout(resolve, 500))
        setProgress(((i + 1) / files.length) * 100)
      }

      toast({
        title: "上传成功",
        description: `已成功上传 ${files.length} 个文件`,
        variant: "success",
        duration: 3000,
      })

      setFiles([])
      onOpenChange(false)
      onUploadSuccess?.()
    } catch (error) {
      console.error("Upload failed:", error)
      toast({
        title: "上传失败",
        description: error instanceof Error ? error.message : "文件上传过程中出现错误",
        variant: "destructive",
      })
    } finally {
      setUploading(false)
      setProgress(0)
    }
  }

  const removeFile = (index: number) => {
    setFiles(files.filter((_, i) => i !== index))
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-xl">
        <DialogHeader>
          <DialogTitle>上传文件</DialogTitle>
          <DialogDescription>选择要上传到云端的文件</DialogDescription>
        </DialogHeader>

        <div
          className="border-2 border-dashed border-border rounded-lg p-12 text-center hover:border-primary/50 transition-colors cursor-pointer"
          onDrop={handleDrop}
          onDragOver={(e) => e.preventDefault()}
          onClick={() => fileInputRef.current?.click()}
        >
          <Upload className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
          <p className="text-sm text-muted-foreground mb-2">拖拽文件到此处或点击选择</p>
          <Button variant="outline" size="sm" type="button">
            选择文件
          </Button>
          <input ref={fileInputRef} type="file" multiple className="hidden" onChange={handleFileSelect} />
        </div>

        {files.length > 0 && (
          <div className="space-y-2 max-h-48 overflow-y-auto">
            {files.map((file, index) => (
              <div key={index} className="flex items-center gap-3 p-3 rounded-lg bg-muted">
                <File className="h-5 w-5 text-muted-foreground flex-shrink-0" />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">{file.name}</p>
                  <p className="text-xs text-muted-foreground">
                    {file.size >= 1024 * 1024
                      ? `${(file.size / (1024 * 1024)).toFixed(1)} MB`
                      : `${(file.size / 1024).toFixed(1)} KB`}
                  </p>
                </div>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 flex-shrink-0"
                  onClick={() => removeFile(index)}
                  disabled={uploading}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            ))}
          </div>
        )}

        {uploading && (
          <div className="space-y-2">
            <Progress value={progress} />
            <p className="text-sm text-muted-foreground text-center">上传中... {Math.round(progress)}%</p>
          </div>
        )}

        <div className="flex gap-3">
          <Button
            variant="outline"
            className="flex-1 bg-transparent"
            onClick={() => onOpenChange(false)}
            disabled={uploading}
          >
            取消
          </Button>
          <Button className="flex-1" onClick={handleUpload} disabled={files.length === 0 || uploading}>
            {uploading ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                上传中
              </>
            ) : (
              `上传 ${files.length} 个文件`
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
